package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.base.framework.util.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.admin.factory.RegionExt;
import com.ldk.admin.factory.RegionFactory;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.framework.entity.Region;
import com.ldk.framework.service.IRegionService;

@Controller
@RequestMapping("/region")
public class RegionController extends BaseController {

	/**
	 * 路由地址
	 */
	private final String route = "region";
	/**
	 * 模块名称
	 */
	private final String module = "地区";
	
	@Autowired
	private IRegionService regionService;
	
	@RequestMapping("/list")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		
		setLinks(map, "", "", module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add");
		map.addAttribute("route", route);
		map.addAttribute("module", module);

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
		
		return new ModelAndView("/region/list");
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<Region> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
									         @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
									         @RequestParam(value="regionName",required=false,defaultValue="") String regionName,
									         @RequestParam(value="regionType",required=false,defaultValue="-1") int regionType,
									         HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		Region query = new Region();
		query.setRegionType(regionType);
		
		if(!StringUtils.isEmpty(regionName)){
			query.setRegionName(regionName);
		}
		CustomPageable pageable = new CustomPageable(offset, limit);
		Page<Region> result = regionService.selectPageList("", query, pageable);
		
		LigerUIGridResult<Region> grid = new LigerUIGridResult<>();
		grid.Total = result.getTotalElements();
		grid.Rows = result.getContent();
		
		return grid;
	}
	
	@ResponseBody
	@RequestMapping(value="/getTreeList",method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<RegionExt> getTreeList()
	{
		Region query = new Region();
		query.setEnabled(true);
		
		List<Region> regions = regionService.selectList("", query);
		
		RegionFactory factory = new RegionFactory();
		return factory.build(regions);
	}
	
	/**
	 * 获取指定地区下的一级地区
	 * @param regionId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getRegion",method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseResult getRegion(@RequestParam(value="regionId",required=false,defaultValue="1") int regionId){
		
		ResponseResult rst = new ResponseResult();
		
		try{
			Region query = new Region();
			query.setParentId(regionId);
			
			List<Region> regions = regionService.selectList("", query);
			
			rst.AddOk(regions);
			
		}
		catch(Exception e){
			rst.AddError("获取地区失败");
		}
		
		return rst;
		
	}
	
	@RequestMapping("/add")
	public ModelAndView add(ModelMap map,HttpServletRequest request,
							HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add", "", "");
		setForm(map, "/"+route+"/insert", null);
		map.addAttribute("route", route);
		map.addAttribute("module", module);
		
		Region model = new Region();
		return new ModelAndView("/region/info","model",model);
	}
	
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable int id, ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		Region query = new Region();
		query.setRegionId(id);
		
		Region model = regionService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		setLinks(map, module+"管理", "/"+route+"/list", "编辑"+module, "/"+route+"/edit/"+id, "", "");
		setForm(map, "/"+route+"/update", null);
		map.addAttribute("route", route);
		map.addAttribute("module", module);
		
		return new ModelAndView("/region/info","model", model);
	}
	
	
	@RequestMapping("/insert")
	public ModelAndView insert(@ModelAttribute("model") Region model, RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		Boolean success = false;
		try{
			
			Region query = new Region();
			query.setParentId(model.getParentId());
			query.setRegionName(model.getRegionName());
			
			long count = regionService.selectCount("", query);
			if(count > 0){
				rst.AddError(String.format("地区名称:%s已经存在", model.getRegionName()));
				
				return new ModelAndView("redirect:/"+route+"/add");
			}
			//操作日志
			this.insertOplog(request,module,"","","添加:"+model.getRegionName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
		    int row = regionService.insert("", model);
		    success = row > 0;
		   
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if (success) {
			rst.AddOk("添加" + module + "成功");
		} else {
			rst.AddError("添加" + module + "失败");
		}
		
		return new ModelAndView("redirect:/"+route+"/add");
	}
	
	@RequestMapping("/update")
	public ModelAndView update(@ModelAttribute("model") Region model, RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		redAttr.addAttribute("id", model.getRegionId());
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		Boolean success = false;
		try{
			
			Region query = new Region();
			query.setParentId(model.getParentId());
			query.setRegionName(model.getRegionName());
			
			Region region = regionService.selectOne("", query);
			if(region != null && !region.getRegionId().equals(model.getRegionId())){
				rst.AddError(String.format("地区名称:%s已经存在", model.getRegionName()));
				
				return new ModelAndView("redirect:/"+route+"/edit/{id}");
			}
		    int row = regionService.updateByKey("", model);
		    success = row > 0;
		   
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if (success) {
			//操作日志
			this.insertOplog(request,module,"","","修改:"+model.getRegionName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
			rst.AddOk("编辑" + module + "成功");
		} else {
			rst.AddError("编辑" + module + "失败");
		}
		
		return new ModelAndView("redirect:/"+route+"/edit/{id}");
	}
	
	/**
	 * 浏览
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/view/{id}")
	public ModelAndView view(@PathVariable int id, ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setViewMode(map, ViewMode.View);
		Region query = new Region();
		query.setRegionId(id);
		Region model = regionService.selectByKey("", query);
		
		map.addAttribute("module", module);
		
		return new ModelAndView("/region/info","model", model);
	}
	
	@ResponseBody
	@RequestMapping("/remove/{id}")
	public ResponseResult remove(@PathVariable int id, HttpServletRequest request){
		
		ResponseResult rst = new ResponseResult();
		if(id < 1)
		{
			rst.AddError("删除"+module+"错误");
		}
		Region query = new Region();
		query.setRegionId(id);
		Region region = regionService.selectByKey("", query);
		//操作日志
		this.insertOplog(request,module,"","","删除:"+region.getRegionName(),this.getAdminUserName(request).toString(),
				Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
		int row  = regionService.deleteByKey("", query);
		if(row > 0){
			rst.AddOk("删除"+module+"成功");
		}
		else{
			rst.AddError("删除"+module+"失败");
		}
		
		return rst;
	}
}
